﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.Authorizations
{
    /// <summary>
    /// 最小年龄的处理器：单Requirement的授权处理器
    /// </summary>
    public class MinimumAgeAuthorizationHandler : AuthorizationHandler<MinimumAgeRequirement>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
        {
            //数据可以从数据库，或声明中获得
            var dateOfBirthClaim = context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth);
            if (dateOfBirthClaim is null)
            {
                return Task.CompletedTask; //标记可以处理后续的授权
            }

            var today = DateTime.Today;
            var dateOfBirth = Convert.ToDateTime(dateOfBirthClaim.Value);
            int calculatedAge = today.Year - dateOfBirth.Year;
            if (dateOfBirth > today.AddYears(-calculatedAge))
            {
                calculatedAge--;
            }

            // 若年龄达到最小年龄要求，则授权通过
            if (calculatedAge >= requirement.MinimumAge)
            {
                context.Succeed(requirement); //认证成功
            }

            //context.Fail();//授权不通过
            return Task.CompletedTask;
        }
    }
}
